package com.app.conrtoller;

import com.alibaba.fastjson.JSON;
import com.app.domain.ExternalResponse;
import com.app.domain.UploadParameter;
import com.app.domain.YjData;
import com.app.domain.kzgs.KzgsResultJson;
import com.app.domain.kzgs.Record;
import com.app.domain.mslc.MslcResultJson;
import com.app.domain.mslc.ReceiveYJData;
import com.app.domain.mslc.Token;
import com.app.service.*;
import com.app.service.algs.TzbbUploadService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 马山梁场
 */
@Slf4j
@RestController
@RequestMapping("/mslc")
public class MslcUploadController {
    @Value("${yj.mslc.serviceHost}")
    private String serviceHost;
    @Value("${yj.mslc.tokenHost}")
    private String tokenHost;
    @Value("${yj.mslc.authorization}")
    private String authorization;
    @Value("${yj.mslc.tenantId}")
    private String tenantId;

    @Autowired
    YjDataService yjDataService;
    @Autowired
    UploadParameterService uploadParameterService;
    @Autowired
    UploadService uploadService;
    @Autowired
    MslcService mslcService;
    @Autowired
    TzbbUploadService tzbbUploadService;

    @RequestMapping("/upload")
    @ResponseBody
    public ExternalResponse upload(@RequestParam(value = "ids[]") String[] ids) throws InterruptedException, UnsupportedEncodingException {
        ExternalResponse externalResponse = null;
        Token token = mslcService.getToken(tokenHost, authorization, tenantId);
        if (token.getAccess_token() == null && "".equals(token.getAccess_token().trim())) {
            externalResponse = new ExternalResponse(0, "token过期", "");
            return externalResponse;
        }
        String accessToken = token.getAccess_token();
        int total = ids.length;
        int succTotal = 0;
        int failTotal = 0;
        StringBuffer responseContent = new StringBuffer();
        responseContent.append("本次共上传数据：【" + total + "】条,");
        List<YjData> yjDataList = yjDataService.findList(ids);
        List<List<YjData>> groupList = new ArrayList<>();
        yjDataList.stream().collect(Collectors.groupingBy(YjData::getBridge_code, Collectors.toList())).forEach((bridge_code, yjDataGroupList) -> {
            groupList.add(yjDataGroupList);
        });
        UploadParameter uploadParameter = uploadParameterService.findOne("36");
        for (List<YjData> yjData : groupList) {
            List<Integer> userIds = yjData.stream().map(o -> o.getId()).collect(Collectors.toList());
            ReceiveYJData receiveYJData = mslcService.getRecord(yjData, uploadParameter);
            String s = JSON.toJSONString(receiveYJData);
            MslcResultJson mslcResultJson = mslcService.sendMessage(serviceHost, s, accessToken);
            if (mslcResultJson.isSuccess() && mslcResultJson.getCode() == 200) {
                for (Integer userId : userIds) {
                    updateState("1", String.valueOf(userId));
                    succTotal++;
                }
            } else {
                for (Integer userId : userIds) {
                    updateState("0", String.valueOf(userId));
                    failTotal++;
                }
            }
        }
        responseContent.append("成功【" + succTotal + "】条,失败" + failTotal + "条");
        externalResponse = new ExternalResponse(0, responseContent.toString(), "");
        return externalResponse;
    }


    @RequestMapping("/add")
    @ResponseBody
    public String add(@RequestParam("deviceCode") String deviceCode, @RequestParam("ductCode") String ductCode, @RequestParam("bridgeCode") String bridgeCode, @RequestParam("mudjackDate") String mudjackDate, @RequestParam("beginTime") String beginTime, @RequestParam("endTime") String endTime) {

        return tzbbUploadService.save(deviceCode, bridgeCode, ductCode, mudjackDate, beginTime, endTime);
    }

    private void updateState(String state, String id) {
        yjDataService.updateById(state, id);
    }
}